package com.arpa.ntocc.basic.api.controller;


import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.PartyGroupCacheDO;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.controller.BaseController;
import com.arpa.ntocc.common.domain.dto.PartyDTO;
import com.arpa.ntocc.common.domain.entity.Party;
import com.arpa.ntocc.common.domain.entity.PartyGroup;
import com.arpa.ntocc.common.domain.enums.PartyTypeEnum;
import com.arpa.ntocc.common.domain.vo.PartyVO;
import com.arpa.ntocc.common.domain.vo.TreeData;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.ntocc.common.security.annotation.NoRepeat;
import com.arpa.ntocc.common.service.IDepartmentService;
import com.arpa.ntocc.common.service.IPartyGroupService;
import com.arpa.ntocc.common.service.IPartyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 员工管理
 * </p>
 *
 * @author 刘秀荣
 * @since 2020-03-13
 */
@Api(tags = "员工管理")
@RestController
@RequestMapping(value = "/staffs", produces = "application/json;charset=UTF-8")
@Log4j2
public class StaffController extends BaseController {

    @Autowired
    private IPartyService iPartyService;
    @Autowired
    private IPartyGroupService partyGroupService;

    @Autowired
    private IDepartmentService departmentService;



    /**
     * 获取员工列表
     *
     * @param partyDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取员工列表", notes = "获取员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = PartyVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(PartyDTO partyDTO, HttpServletRequest request) {
        //获取登录用户所属机构
        PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
        if (partyGroupCacheDO.getLevel() > 0) {
            partyDTO.setBranchCode(partyGroupCacheDO.getCode());
        }

        PartyVO partyVoSum = iPartyService.queryListSum(partyDTO);
        List<PartyVO> partyVOList = iPartyService.queryList(partyDTO);

        Page returnPage = new Page(partyDTO.getPageNum(), partyDTO.getPageSize());
        returnPage.setRecords(partyVOList);
        returnPage.setTotal(partyVoSum.getTotal());
        returnPage.setSumObject(partyVoSum);
        return Result.ok().data(returnPage);
    }

    /**
     * 添加 员工
     *
     * @param entity  PartyDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 员工 ", notes = "添加 员工 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @NoRepeat(time = 2000)
    @PostMapping()
    public Result create(@RequestBody @Valid PartyDTO entity, HttpServletRequest request) {
        entity.setBranchCode(UserUtil.getBranchCode());
        iPartyService.saveStaff(entity);
        return Result.ok("员工添加成功");
    }

    /**
     * 获取员工详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取员工详情", notes = "获取员工详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "用户code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Party.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result party(@PathVariable String code, HttpServletRequest request) {
        try {
            PartyVO entity = iPartyService.queryPartyInfo(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改员工
     *
     * @param entity  用户
     * @param request
     * @return
     */
    @ApiOperation(value = "修改员工", notes = "修改员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Valid PartyDTO entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        int updateNum = iPartyService.updateStaffByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("员工信息修改成功,更新" + updateNum + "条数据！");
        }
    }




    /**
     * 获取所有没有账号的员工列表
     *
     * @param partyDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取所有没有账号的员工列表", notes = "获取所有没有账号的员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = PartyVO.class))
    @NeedLogin
    @GetMapping("notHaveUserLoginStafflist")
    public Result allNotHaveUserLoginStafflist(PartyDTO partyDTO, HttpServletRequest request) {
        //获取登录用户所属机构
        PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
        if (partyGroupCacheDO.getLevel() > 0) {
            partyDTO.setBranchCode(partyGroupCacheDO.getCode());
        }
        List<PartyVO> partyVOList = iPartyService.findNotHaveUserLoginStaffs(partyDTO);
        return Result.ok().data(partyVOList);
    }


    /**
     * 查询非业务员下拉列表数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "员工下拉列表数据", notes = "员工下拉列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "branchCode", value = "当前用户所属机构CODE", paramType = "query", dataType = "string", defaultValue = "",required = true)
    })
    @NeedLogin
    @GetMapping(value = "chooseData")
    public Result chooseData(
            @RequestParam(value = "code", defaultValue = "")  String code,
                                        @RequestParam(value = "branchCode")  String branchCode,
                                        HttpServletRequest request) {
        try {
            List<Party> staffs = iPartyService.list(new QueryWrapper<Party>().lambda().eq(Party::getBranchCode,branchCode)
                    .in(Party::getPartyType,PartyTypeEnum.GROUP_ADMIN.getValue(),PartyTypeEnum.USER.getValue()));
            return Result.ok().data(staffs);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 查询非业务员下拉列表数据(默认的组织机构，用来预打包等用途)
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "员工下拉列表数据", notes = "员工下拉列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
    })
    @NeedLogin
    @GetMapping(value = "chooseDataDefaultBranchCode")
    public Result chooseDataDefaultBranchCode(
            HttpServletRequest request) {
        try {
            String branchCode = UserUtil.getBranchCode();
            PartyGroup partyGroup = partyGroupService.getByCode(branchCode);
            List<Party> staffs;
            //todo rfwang 员工查询逻辑待确认
          /*  if (partyGroup.getLevel()>0){
                staffs = iPartyService.list(new QueryWrapper<Party>().lambda().eq(Party::getBranchCode,branchCode).in(Party::getPartyType,PartyTypeEnum.PLAT_ADMIN,PartyTypeEnum.STAFF));
            }else{
                staffs = iPartyService.list(new QueryWrapper<Party>().lambda().in(Party::getPartyType,PartyTypeEnum.PLAT_ADMIN,PartyTypeEnum.STAFF));
            }*/
            staffs = iPartyService.list(new QueryWrapper<Party>().lambda().eq(Party::getBranchCode,branchCode).in(Party::getPartyType,PartyTypeEnum.GROUP_ADMIN,PartyTypeEnum.USER));
            return Result.ok().data(staffs);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 员工级联数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 员工级联数据", notes = "获取 员工级联数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = TreeData.class))
    @NeedLogin
    @GetMapping("/cascadeData")
    public Result cascadeData(HttpServletRequest request) {
        try {
            List<TreeData> cascadeData = departmentService.cascadeData();
            return Result.ok().data(cascadeData);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取员工打印列表
     *
     * @param partyDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取员工导出列表", notes = "获取员工导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = PartyVO.class))
    @NeedLogin
    @GetMapping("/exportStaffList")
    public Result exportStaffList(PartyDTO partyDTO, HttpServletRequest request) {
        //获取登录用户所属机构
        PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
        if (partyGroupCacheDO.getLevel() > 0) {
            partyDTO.setBranchCode(partyGroupCacheDO.getCode());
        }
        partyDTO.setPageNum(1);
        partyDTO.setPageSize(Integer.MAX_VALUE);
        List<PartyVO> partyVOList = iPartyService.queryList(partyDTO);

        Page returnPage = new Page(partyDTO.getPageNum(), partyDTO.getPageSize());
        returnPage.setRecords(partyVOList);
        return Result.ok().data(returnPage);
    }

}
